<div>
  <div class="mb-5">
    <a-input-search v-model:value="searchValue" placeholder="输入你想要查询的电视剧名称" enter-button
      @search="searchHandle"></a-input-search>
  </div>
  <div>
    <div class="mb-5">
      <div class="flex justify-between">
        <a-typography-title :level="3">电视剧列表</a-typography-title>
        <div>
          <a-button type="primary" class="flex" @click="goto('/admin/tv/add?menu_open=tv')">
            <template #icon>
              <svg class="icon" aria-hidden="true" style="color: white">
                <use xlink:href="#icon-jiahao"></use>
              </svg>
            </template>
            <span class="ml-2">新增</span>
          </a-button>
        </div>
      </div>
      <easy-data-table :headers="cols" :items="tvList" hide-footer>

        <template #item-pic="item">
          <div class="p-1">
            <a-image :src="item.pic" width="65px" height="97px"></a-image>
          </div>
        </template>

        <template #item-show="item">
          <a-switch @change="showChangeHandle(item)" :checked="item.show=='1'?true: false" checked-children="显示"
            un-checked-children="隐藏"></a-switch>
        </template>

        <template #item-name="item">
          <a-input v-if="editableData[item.id]" v-model:value="editableData[item.id].name" class="text-xs"
            style="margin: -5px 0"></a-input>
          <template v-else>
            <span> {{item.name}}</span>
          </template>
        </template>

        <template #item-classify="item">
          <a-select style="min-width: 140px;" v-if="editableData[item.id]"
            v-model:value="editableData[item.id].classify" :options="classifyList" mode="multiple">
          </a-select>
          <template v-else>
            <span> {{item.classify}}</span>
          </template>
        </template>

        <template #item-score="item">
          <a-input v-if="editableData[item.id]" v-model:value="editableData[item.id].score" class="text-xs"
            style="margin: -5px 0"></a-input>
          <template v-else>
            <span> {{item.score}}</span>
          </template>
        </template>

        <template #item-actors="item">
          <a-input v-if="editableData[item.id]" v-model:value="editableData[item.id].actors" class="text-xs"
            style="margin: -5px 0"></a-input>
          <template v-else>
            <span> {{item.actors}}</span>
          </template>
        </template>

        <template #item-desc="item">
          <div class="p-3 text-xs">
            <a-textarea v-if="editableData[item.id]" v-model:value="editableData[item.id].desc" class="text-xs"
              :auto-size="{ minRows: 2, maxRows: 6 }"></a-textarea>
            <template v-else>
              <div style="font-size: 12px;">
                {{item.desc}}
              </div>
            </template>
          </div>
        </template>

        <template #item-action="item">
          <span v-if="editableData[item.id]">
            <span class="span_link cursor-pointer mr-2" @click="tableSaveHandle(item)">保存</span>
            <a-popconfirm title="确认取消编辑吗？" ok-text="确定" cancel-text="取消" @confirm="tableCancelHandle(item)">
              <span class="span_link cursor-pointer mr-2">取消</span>
            </a-popconfirm>
          </span>
          <span v-else class="span_link cursor-pointer mr-2" @click="tableEditHandle(item)">编辑</span>

          <a-popconfirm title="确定要删除这部电视剧吗？" ok-text="确定" cancel-text="取消" @confirm="confirmDelete(item)">
            <span class="span_link cursor-pointer mr-2">删除</span>
          </a-popconfirm>
          <span class="span_link cursor-pointer " @click="gotoBlank(`/detail?id=${item.id}&kind=tv&play=1`)">前往观剧</span>
        </template>
        <template #item-action_pic="item">
          <span v-if="fileData[item.id]">
            <span class="span_link cursor-pointer mr-2" @click="savePicHandle(item)">保存</span>
            <span class="span_link cursor-pointer mr-2" @click="canclePicHandle(item)">取消</span>
          </span>
          <span class="span_link cursor-pointer mr-2" @click="changePicHandle(item)" v-else>修改封面</span>
          <span v-show="false">
            <input :id="'file_dom_'+item.id" type="file" accept="image/*" @change="getPicHandle(item)">
          </span>
        </template>

        <template #empty-message>
          <div class="flex items-center flex-col">
            <div>
              暂时还没有数据哟，<span class="span_link cursor-pointer" @click="goto('/admin/tv/add?menu_open=tv')">前往添加</span>
            </div>
            <div style="width:120px; height: 120px;">
              <img src="/public/images/no_data.svg" />
            </div>
          </div>
        </template>

      </easy-data-table>
    </div>
    <div class="flex justify-end">
      <a-pagination v-model:current="pagination.current" v-model:pageSize="pagination.pageSize"
        :show-size-changer="false" :total="pagination.total" @change="paginationChangeHandle"></a-pagination>
    </div>
  </div>

</div>
<script>
  let columnsData = [
    {
      text: '名称',
      value: 'name',
      width: 120,
    },
    {
      text: '封面',
      value: 'pic',
      width: 80
    },
    {
      text: '分类',
      value: 'classify',
      width: 160
    },
    {
      text: '评分',
      value: 'score',
      width: 80
    },
    {
      text: '主演',
      value: 'actors',
      width: 240
    },
    {
      text: '详情',
      value: 'desc',
      width: 500
    },
    {
      text: '是否展示',
      value: 'show',
      width: 90
    },
    {
      text: '封面操作',
      value: 'action_pic',
      width: 100
    },
    {
      text: '操作',
      value: 'action',
    },
  ];

  function useMain() {
    const searchValue = ref('');
    const tvList = ref([]);
    const pagination = ref({
      total: 0,
      pageSize: 10,
      current: 1,
    });
    const classifyList = ref([]);
    const editableData = reactive({});
    const fileData = reactive({});

    const tableEditHandle = params => {
      let id = params.id;
      editableData[id] = _.cloneDeep(tvList.value.filter(item => id === item.id)[0]);
      editableData[id].classify = editableData[id].classify.split("/")
    };
    const tableSaveHandle = async params => {
      let id = params.id;
      editableData[id].classify = editableData[id].classify.join("/")
      let tmp = Object.assign(tvList.value.filter(item => id === item.id)[0], editableData[id]);
      let body = _.pick(tmp, ['name', 'score', 'desc', 'actors', 'classify', 'id']);
      let ret = await axios.post('/v1/web/tv/update', body);
      delete editableData[id];
      if (ret.data.code != 200) {
        Hint.error("保存修改失败，请稍后重试~");
        return;
      }
      reload({ hint_msg: ret.data.msg });

    };
    const tableCancelHandle = params => {
      delete editableData[params.id];
    };
    const showChangeHandle = async params => {
      console.log(params)
      try {
        let ret = await axios.post('/v1/web/tv/update', { id: params.id, show: params.show == 1 ? false : true });
        if (ret.data.code != 200) {
          Hint.error("隐藏显示失败，请稍后重试~");
          return;
        }
        reload({ hint_msg: ret.data.msg, });
      } catch (e) {
        let msg = '隐藏显示失败，请稍后重试~';
        console.log(e, msg);
        Hint.error(msg);
      }

    };
    const changePicHandle = params => {
      let dom = document.querySelector("#file_dom_" + params.id);
      dom.click();
    };
    const getPicHandle = params => {
      let dom = document.querySelector("#file_dom_" + params.id);
      fileData[params.id] = dom.files[0];
      Hint.success("选择封面成功，点击保存确认修改~");
    }
    const savePicHandle = async params => {
      try {
        let file = fileData[params.id];
        let fm = new FormData();
        fm.append('file', file);
        let upRet = await axios.post('/v1/upload/pic?' + Qs.stringify({
          word: params.word,
          id: 1,
          type: 'tv'
        }), fm, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        let ret = await axios.post('/v1/web/tv/update', { id: params.id, pic: upRet.data.data.filename });
        reload({ hint_msg: "修改封面信息成功", });
      } catch (e) {
        let msg = '修改封面信息失败,请稍后再试~';
        console.log(e, msg);
        Hint.error(msg);
      }
    }
    const canclePicHandle = params => {
      let dom = document.querySelector("#file_dom_" + params.id);
      dom.value = "";
      delete fileData[params.id]; 
    }
    const confirmDelete = async params => {
      let { id, word,name } = params;
      try {
        let ret = await axios.post('/v1/web/tv/delete', { id, word, name });
        if (ret.data.code != 200) {
          Hint.error(ret.data.msg);
        }
        reload({ hint_msg: ret.data.msg, });
      } catch (e) {
        let msg = '删除电视剧失败,请稍后再试~';
        console.log(e, msg);
        Hint.error(msg);
      }
    }

    const searchHandle = async () => {
      if (searchValue.value.length < 1) {
        Hint.warn('请输入你想要搜索的名称');
        return;
      }
      let param = Qs.parse(window.location.href.split("?")[1])
      param.search = searchValue.value;
      param.table_current = 1;
      window.location.href = window.location.pathname + '?' + Qs.stringify(param)
    };
    const getTvDetail = async () => {
      try {
        let ret = await getTeleplayInfo();
      } catch (e) {
        console.log(e);
        Hint.warn('获取电视信息失败');
      }
    };
    const getClassify = async () => {
      try {
        let ret = await await axios.post('/v1/web/tv/classify', { type: 'all' });
        let dat = ret.data.data;
        classifyList.value = dat.map(a => ({
          label: a.name,
          value: a.name
        }));
      } catch (e) {
        let msg = `获取电视剧分类失败`;
        Hint.error(msg);
        console.log(msg, e);
      }
    };
    const getTvList = async (limit, offset, query = {}) => {
      try {
        let ret = await axios.post('/v1/web/tv/list', {
          limit, offset: limit * (offset - 1), query
        });
        let dat = ret.data.data;
        pagination.value.total = dat.count;
        tvList.value = dat.rows.map(a => ({ ...a, pic: base.public_tv_img + a.pic }));
      } catch (e) {
        let msg = `获取电视列表失败`;
        console.log(msg, e);
        Hint.success(msg);
      }
    };

    const paginationChangeHandle = async (page, pageSize) => {
      window.location.href = `/admin/tv/list?menu_open=tv&table_current=${page}`
    };

    onMounted(async () => {
      let urlParams = Qs.parse(window.location.href.split("?")[1]);
      let table_current = urlParams?.table_current ?? 1;
      pagination.value.current = table_current;
      let query = {}
      if (urlParams?.search != undefined) {
        query.name = urlParams.search;
        searchValue.value = urlParams.search;
      }

      await getTvList(pagination.value.pageSize, pagination.value.current, query);
      await getClassify();
    });
    return {
      searchValue,
      tvList,
      pagination,
      cols: ref(columnsData),
      editableData,
      classifyList,
      fileData,
      confirmDelete,
      searchHandle,
      paginationChangeHandle,
      tableEditHandle,
      tableSaveHandle,
      tableCancelHandle,
      showChangeHandle,
      changePicHandle,
      getPicHandle,
      savePicHandle,
      canclePicHandle,
    };
  }
</script>